package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.ConstantPropertiesUtil;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成并返回二维码数据
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public R genQrConnect(HttpSession session) throws UnsupportedEncodingException {

        Map<String, Object> map = new HashMap<>();
        String requireUrl = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
        //这些数据都是固定的
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirectUri", requireUrl);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis()+"");//System.currentTimeMillis()+""
        return R.ok().data(map);

    }

    @GetMapping("callback")
    public String callback(String code, String state, HttpSession session) {

        //code是生成的额临时票据
        System.out.println("code = " + code);
        System.out.println("state = " + state);

        //拿着生成出来的code的和appid和app_secret去使用httpclint去请求接口
        StringBuffer stringUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        //这里的%S是占位符就是代码这里要传递参数
        String format = String.format(stringUrl.toString(), ConstantPropertiesUtil.WX_OPEN_APP_ID, ConstantPropertiesUtil.WX_OPEN_APP_SECRET, code);
        //format中的参数和上面的%s的位置是对应的，顺序不可以写错

        try {
            //使用httpclint发送请求
            String accesstokenInfo = HttpClientUtils.get(format);
            //打印accesstokeninfo查看返回的数据，访问的这个接口是腾讯的，不需要我们去做
            System.out.println("accesstokenInfo = " + accesstokenInfo);
            //返回数据
//            accesstokenInfo = {
//                    "access_token": "52_ixsMim4AOA_4eIxaq9rGF05idAaQplCVYI7pXbLioZd_F8QbD2LbbihPnSFIO-Ke-13UpRkMy5dQYkzp5NXEfVRp5StOAlZSRrMd8ZClHtk",
//                    "expires_in": 7200,
//                    "refresh_token": "52_hewlUYe3vZklHZDGC0KRZHw8jLbgetmQQ09biQ4sx6kVSBkGEB7RT3r4Ay2UGF69F0i2EUwhflUqaKrS4figwFUXKBpA-2q74qwn2HgSCLg",
//                    "openid": "o3_SC56Ro6LrRMXWqtYbGpijHdMo",
//                    "scope": "snsapi_login",
//                    "unionid": "oWgGz1K9Axgs9P8l0wT49i1jboeA"
//            }
//            将返回数据中的access_token和openid取出
            JSONObject jsonObject = JSONObject.parseObject(accesstokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //取出之后拿着我们生成的openid和access_token继续去发送请求，获取扫码的用户信息
            StringBuffer httpUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            //将%S的数据封装到地址中
            String format1 = String.format(httpUrl.toString(), access_token, openid);

            //使用httpclint进行请求
            String resultInfo = HttpClientUtils.get(format1);
            //打印输出数据
            System.out.println("resultInfo = " + resultInfo);
//            resultInfo = {
//                    "openid": "o3_SC56Ro6LrRMXWqtYbGpijHdMo",
//                    "nickname": "C.",
//                    "sex": 0,
//                    "language": "",
//                    "city": "",
//                    "province": "",
//                    "country": "",
//                    "headimgurl": "https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/oibXNNKmCZ0MVFbw8J0icLNeOKuzaoSrEHkc7rB8vdm21AINfBGx8CLhPxqzFQ59rYMibPCaxsxl6zmXzGjYnJVEA\/132",
//                    "privilege": [],
//            "unionid": "oWgGz1K9Axgs9P8l0wT49i1jboeA"
//            }

            //将用户昵称和头像地址取出，如果是首次登录的话，就存到数据库
            JSONObject jsonObject1 = JSONObject.parseObject(resultInfo);
            //用户的微信昵称
            String nickname = jsonObject1.getString("nickname");
            //用户的头像地址
            String headimgurl = jsonObject1.getString("headimgurl");

            //使用openid查询是否是首次登录
            UserInfo userInfo = userInfoService.getByOpenId(openid);
            if(userInfo == null){
                userInfo = new UserInfo();
                userInfo.setStatus(1);
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfoService.save(userInfo);
            }
            //准备返回的数据
            Map<String,String> map = new HashMap<>();
            String name = userInfo.getName();
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if(StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            //判断userInfo是否有手机号，如果手机号为空，返回openid
            //如果手机号不为空，返回openid值是空字符串
            //前端判断：如果openid不为空，绑定手机号，如果openid为空，不需要绑定手机号
            if(StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            //使用jwt生成token字符串
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            //使用重定向跳转页面，携带参数，这里的跳转页面其实就是中转了一下，不然的话不好实现下一步的 操作
            return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+URLEncoder.encode(map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }

}
